﻿using UnityEngine;

namespace Framework
{
    public class UnitySingleton<T> : MonoBehaviour where T : MonoBehaviour
    {
        protected static T _instance;

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = (T)FindObjectOfType(typeof(T));
                    if (_instance == null)
                    {
                        GameObject singleton = new GameObject();
                        _instance = singleton.AddComponent<T>();
                        singleton.name = "(singleton) " + typeof(T).ToString();
                        if(Application.isPlaying)
                            DontDestroyOnLoad(singleton);
                    }
                }
                return _instance;
            }
        }
    }

    public abstract class Singleton<T> : System.Object where T : Singleton<T>, new()
    {
        private static T _instance = null;

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new T();
                    _instance.Initialize();
                }
                return _instance;
            }
        }

        protected virtual void Initialize()
        {

        }
    }
}
